<template>
  <div class="body-box">
    <div class="login-box">
      <!-- <div :span="24" class="header-box">
        <span>公共机构双控双碳数字管家</span>
        <img src="@/assets/images/login/headerBg.png" alt="" />
      </div> -->
      <div class="mid-box">
        <div class="mid-title">
          <span>公共机构双控双碳数字管家</span>
        </div>
        <div class="formBox">
          <div class="change-picture" @click="changeLoginway">
            <img
              v-if="!showQrlogin"
              src="@/assets/images/login/login-qrlogin.png"
              alt=""
            />
            <img
              v-show="showQrlogin"
              src="@/assets/images/login/login-accountlogin.png"
              alt=""
            />
          </div>
          <div v-if="showQrlogin" class="login-qr">
            <iframe
              style="border: medium none"
              width="300px"
              height="300px"
              :src="
                'https://login-pro.ding.zj.gov.cn/oauth2/auth.htm?response_type=code&client_id=' +
                clientId +
                '&redirect_uri=' +
                hookUrl +
                '&scope=get_user_info&authType=QRCODE&embedMode=true'
              "
            >
            </iframe>
          </div>
          <div class="title" v-show="!showQrlogin">
            <div class="title-left">
              <img src="@/assets/images/login/zzdLogo.png" alt="dark" />
              <span>浙政钉</span>
            </div>
            <span class="title-tig">扫码登录更安全</span>
          </div>
          <el-form
            ref="loginForm"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            v-show="!showQrlogin"
          >
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                type="text"
                auto-complete="off"
                placeholder="账号"
              >
                <!-- :readonly="readonlyInput"
                @focus="cancelReadOnly()" -->
                <img
                  slot="prefix"
                  src="@/assets/images/login/user.png"
                  alt="dark"
                  class="el-input__icon input-icon"
                />
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                auto-complete="off"
                placeholder="密码"
                show-password
                @keyup.enter.native="handleLogin"
              >
                <!-- :readonly="readonlyInput2"
                @focus="cancelReadOnly2()" -->
                <img
                  slot="prefix"
                  src="@/assets/images/login/password.png"
                  alt="dark"
                  class="el-input__icon input-icon"
                />
              </el-input>
            </el-form-item>
            <el-form-item prop="code" v-if="captchaOnOff">
              <el-input
                v-model="loginForm.code"
                auto-complete="off"
                placeholder="验证码"
                style="width: 63%"
                @keyup.enter.native="handleLogin"
                class="code-input"
              >
                <img
                  slot="prefix"
                  src="@/assets/images/login/code.png"
                  alt="dark"
                  class="el-input__icon input-icon"
                />
              </el-input>
              <div class="login-code">
                <img :src="codeUrl" @click="getCode" class="login-code-img" />
              </div>
            </el-form-item>
            <el-checkbox v-model="loginForm.rememberMe" class="login-checkbox">
              记住密码
            </el-checkbox>
            <!-- <div style="float: right" v-if="register">
                <router-link class="link-type" :to="'/register'"
                  >立即注册</router-link
                >
              </div> -->
            <el-form-item>
              <el-button
                :loading="loading"
                size="small"
                type="primary"
                class="btn"
                @click.native.prevent="handleLogin"
              >
                <span v-if="!loading">登 录</span>
                <span v-else>登 录 中...</span>
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!--  底部  -->
      <div class="el-login-footer">
        <img
          src="@/assets/images/login/logo.png"
          alt="dark"
          class="el-input__icon"
        />
        <div class="info">
          <p>技术支持：浙江弄潮儿智慧科技有限公司 支持电话：18667145678</p>
          <p>
            编译时间:{{ BUILD_DATE }}, 所在分支:{{ BRANCH }} 版本号:{{
              VERSION
            }}
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import { MessageBox } from "element-ui";
import { getInfo, getDingInfo } from "@/api/login";
import { getRouters } from "@/api/menu";
import { encryptData } from "@/utils/index";

export default {
  name: "Login",
  data() {
    return {
      list: [],
      VERSION: process.env.VUE_APP_VERSION,
      BUILD_DATE: process.env.VUE_APP_BUILD_DATE,
      BRANCH: process.env.VUE_APP_BRANCH,
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
      },
      loading: false,
      // 验证码开关
      captchaOnOff: true,
      // 注册开关
      register: false,
      redirect: undefined,
      showQrlogin: false,
      // configValue: "1",
      // appSign: "ocean_dingoa",
      // hookUrl: "https://ocean.zrzyt.zj.gov.cn/",
      clientId: "zssggjgstskszgj_dingoa", // 登录系统辨识码
      hookUrl: "http://zdegj.zsjgj.zhoushan.gov.cn/",
      readonlyInput: true,
      readonlyInput2: true,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  mounted() {
    window.addEventListener("message", this.onMessage);
  },
  destroyed() {
    // 在组件生命周期结束的时候销毁。
    window.removeEventListener("message", this.onMessage);
  },
  methods: {
    cancelReadOnly() {
      this.readonlyInput = false;
      this.readonlyInput2 = true;
    },
    cancelReadOnly2() {
      this.readonlyInput = true;
      this.readonlyInput2 = false;
    },
    onMessage(event) {
      // 这里的event.data 就是登录成功的信息
      // 数据格式：{ "code": "aaaa", "state": "bbbb" }
      console.log(event, 1);
      if (event.data.code) {
        console.log(event.data.code, 2);
        this.handleDingLogin({ code: event.data.code });
      }
    },
    handleDingLogin(params) {
      console.log(params, "请求参数");
      this.$store
        .dispatch("DingLogin", params)
        .then((res) => {
          console.log(res, 3);
          if (res.code === 700) {
            // this.$message.warning(res.msg);
            MessageBox.confirm(res.msg, "系统提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                this.$store.dispatch("LogOut").then(() => {
                  location.href = "/index";
                });
              })
              .catch(() => {});

            return false;
          }
          // this.$router.push("/titlePage").catch(() => {});
          // this.$router.push("/index").catch(() => {});
          // setTimeout(() => {
          //   this.handleGobig();
          // }, 200);
          this.checkInfoGo();
        })
        .catch((err) => {});
    },
    changeLoginway() {
      this.showQrlogin = !this.showQrlogin;
    },
    getCode() {
      // this.captchaOnOff = false;
      getCodeImg().then((res) => {
        this.captchaOnOff =
          res.captchaOnOff === undefined ? true : res.captchaOnOff;
        if (this.captchaOnOff) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), {
              expires: 30,
            });
            Cookies.set("rememberMe", this.loginForm.rememberMe, {
              expires: 30,
            });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }
          let aesPassword = encryptData(
            this.loginForm.password,
            "3dV6QotxXtm4FXwv"
          );
          // console.log(aesPassword, "pppp");
          let form = { ...this.loginForm };
          form.password = aesPassword;
          setTimeout(() => {
            this.$store
              .dispatch("Login", form)
              .then((res) => {
                this.checkInfoGo();
              })
              .catch(() => {
                this.loading = false;
                if (this.captchaOnOff) {
                  this.getCode();
                }
              });
          }, 100);
        }
      });
    },
    // 对比角色roles判断跳转
    checkInfoGo() {
      getRouters()
        .then((res) => {
          const tiledRouters = this.resetRouer(res.data);
          if (tiledRouters.includes("//cockpit")) {
            // 去往大屏
            setTimeout(() => {
              this.handleGobig();
            }, 200);
          } else {
            // this.$router.push("/index").catch(() => {}); // 去往首页
            this.$router.push("/work/general").catch(() => {}); // 去往导航页
          }
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
      // getInfo()
      //   .then((res) => {
      //     if (res.code === 700) {
      //       this.$message.warning(res.msg);
      //       return false;
      //     }
      //     let roles = res?.roles ?? [];
      //     if (roles.includes("cockpit_leader")) {
      //       // 去往大屏
      //       setTimeout(() => {
      //         this.handleGobig();
      //       }, 200);
      //     } else {
      //       // this.$router.push("/index").catch(() => {}); // 去往首页
      //       this.$router.push("/titlePage").catch(() => {}); // 去往导航页
      //     }
      //   })
      //   .catch(() => {
      //     // this.$message.error("系统错误,请联系管理员!");
      //   });
    },
    resetRouer(data, path) {
      let that = this;
      data.forEach((item) => {
        if (item.children && item.children.length > 0) {
          if (item.component === "Layout") {
            that.list.push(item.path);
          } else {
            that.list.push(path + "/" + item.path);
          }
          that.resetRouer(item.children, item.path);
        } else {
          if (item.component === "Layout") {
            that.list.push(item.path);
          } else {
            that.list.push(path + "/" + item.path);
          }
        }
      });
      return that.list;
    },

    // 去往大屏驾驶舱
    handleGobig() {
      if (process.env.NODE_ENV === "development") {
        // let token = localStorage.getItem("t-token");
        // window.location = process.env.VUE_APP_SIP + "?token=" + token;
        this.$router.push("/work/general").catch(() => {}); // 去往导航页
      } else {
        // 生产环境待处理
        window.open(this.$router.resolve({ path: "/dt" }).href, "_parent");
      }
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@media screen and (min-width: 0px) and (max-width: 2880px) {
  @keyframes animateBg {
    0% {
      backdrop-filter: blur(5px);
      opacity: 0.9;
    }
    30% {
      backdrop-filter: blur(3px);
      opacity: 1;
    }
    60% {
      backdrop-filter: blur(1px);
      opacity: 1;
    }
    to {
      backdrop-filter: blur(0);
      opacity: 1;
      background: url("~@/assets/images/login/loginBg-small.png") center bottom
        no-repeat;
      background-size: cover;
    }
  }

  .login-box {
    background: url("~@/assets/images/login/loginBg-small-mini.png") center
      bottom no-repeat;
  }
}
@media screen and (min-width: 2881px) {
  @keyframes animateBg {
    0% {
      backdrop-filter: blur(5px);
      opacity: 0.9;
    }
    30% {
      backdrop-filter: blur(3px);
      opacity: 1;
    }
    60% {
      backdrop-filter: blur(1px);
      opacity: 1;
    }
    to {
      backdrop-filter: blur(0);
      opacity: 1;
      background: url("~@/assets/images/login/loginBg-big.png") center bottom
        no-repeat;
      background-size: cover;
    }
  }
  .login-box {
    background: url("~@/assets/images/login/loginBg-big-mini.png") center bottom
      no-repeat;
  }
}
@keyframes changeLoginway {
  from {
    opacity: 0.5;
    transform: translateY(100px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
.login-way-change {
  animation-name: changeLoginway;
  animation-direction: 10s;
}
.body-box {
  width: 100%;
  height: 100%;
  position: relative;
}
.login-box {
  min-width: 1250px;
  overflow: hidden;
  margin: 0 auto;
  height: 100%;
  background-size: cover;
  animation: animateBg 1.6s ease-in;
  animation-fill-mode: forwards;
  // .header-box {
  //   margin-top: 5px;
  //   width: 100%;
  //   display: flex;
  //   align-items: center;
  //   justify-content: center;
  //   span {
  //     z-index: 2;
  //     font-size: 32px;
  //     font-family: PingFang-SC-Bold, PingFang-SC;
  //     font-weight: bold;
  //     // color: #ffffff;
  //     line-height: 45px;
  //     cursor: default;
  //     background-image: -webkit-linear-gradient(top, #00ccff, #ffffff);
  //     -webkit-background-clip: text;
  //     -webkit-text-fill-color: transparent;
  //   }
  //   img {
  //     position: absolute;
  //     width: 1920px;
  //     height: 66px;
  //   }
  // }
}
.mid-box {
  position: relative;
  width: 100%;
  // height: 220px;
  top: 150px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  // background: rgba(0, 0, 0, 0.5);
  .mid-title {
    margin-bottom: 50px;
    span {
      font-size: 60px;
      font-family: PingFang-SC-Medium, PingFang-SC;
      font-weight: 500;
      color: #ffffff;
      line-height: 84px;
      letter-spacing: 10px;
      text-shadow: 0px 2px 4px rgba(0, 0, 0, 0.17);
    }
  }
}
.formBox {
  position: relative;
  width: 360px;
  height: 380px;
  background: rgba(0, 0, 0, 0.5);
  box-shadow: 0px 2px 10px 4px rgba(0, 0, 0, 0.24);
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .change-picture {
    position: absolute;
    right: 0px;
    top: 0px;
    z-index: 9;
    img {
      height: 65px;
      width: 71px;
      cursor: pointer;
    }
  }
  .title {
    width: 270px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .title-left {
      display: flex;
      align-items: center;
      img {
        width: 26px;
        height: 26px;
        margin-right: 10px;
        vertical-align: middle;
      }
      span {
        font-size: 28px;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        color: #ffffff;
        line-height: 40px;
      }
    }
    .title-tig {
      font-size: 16px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #ffffff;
      line-height: 22px;
    }
  }
  .login-qr {
    width: 320px;
    height: 320px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .login-form {
    margin-top: 30px;
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;
    .el-input {
      height: 38px;
      width: 270px;
      ::v-deep input {
        height: 38px;
        background: rgba(0, 0, 0, 0.5);
        // border-color: #30aaff;
        border: none;
        border-bottom: 1px solid #444444;
        padding-left: 35px;
        color: #ffffff;
      }
    }
    .code-input {
      margin-left: -22px;
    }
    .input-icon {
      height: 24px;
      width: 24px;
      margin-left: 2px;
      vertical-align: middle;
    }
    ::v-deep.btn {
      width: 270px;
      height: 40px;
      background: #05a3fa;
      border-color: #409eff !important;
      border-radius: 5px;
      span {
        font-size: 20px;
        font-family: PingFang-SC-Medium, PingFang-SC;
        font-weight: 500;
        color: #ffffff;
        line-height: 28px;
      }
      // background: linear-gradient(180deg, #00f9ff 0%, #00f1fd 100%);
    }
    .login-checkbox {
      margin: 0px 0 20px -188px;
      ::v-deep .el-checkbox__label {
        color: #fff;
      }
      ::v-deep.el-checkbox__inner {
        border-color: #409eff;
        // zoom: 1.4;
        // border: 1px solid #30aaff;
      }
      ::v-deep.is-checked {
        .el-checkbox__inner {
          background-color: #409eff;
          // zoom: 1.4;
          // border: 1px solid #30aaff;
        }
      }
    }
    .login-code {
      width: 33%;
      height: 38px;
      float: right;
      img {
        cursor: pointer;
        vertical-align: middle;
      }
    }
    .login-code-img {
      position: absolute;
      height: 38px;
      top: -5px;
    }
  }
}
.sign {
  position: fixed;
  bottom: 50px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  div {
    font-size: 20px;
    text-align: center;
    color: #ffffff;
    width: 20%;
    h4 {
      margin: 10px;
    }
    img {
      height: 100px;
    }
  }
  div:nth-child(even) {
    padding-top: 100px;
  }
}
.el-login-footer {
  width: 100%;
  min-width: 1220px;
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 10px;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
  display: flex;
  justify-content: center;
  align-items: center;
  .el-input__icon {
    vertical-align: middle;
    margin-right: 10px;
  }
  .info {
    p {
      margin: 5px 0;
      line-height: initial;
    }
  }
}
</style>
